<script setup lang='ts'>
import { FolderOpened } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { reqGetProject } from '../../apis/project'
import { ElMessageBox, ElMessage } from 'element-plus'
import { reqJoinMemberProjectById } from '../../apis/project/index'
import useUserStore from '../../store/modules/user'
import Avatar from '../../components/avatar.vue'
import useSettingStore from '../../store/modules/setting'
import {reqUpdateUserInfo} from '../../apis/user/index'
import { useRouter } from 'vue-router'
import type {ProjectItem} from '../../apis/project/type'

const $router = useRouter()
const useSetting = useSettingStore()
const dialogVisible = ref<boolean>(false)
const useUser = useUserStore()
const projects = ref<ProjectItem[]>([])
const loading = ref(false)
const paginationData = ref({
  current: 1,
  pageSize: 10,
  total: 0
})
const userInfo = ref({
  name: useUser.userName,
  role:useUser.role,
  email:useUser.email,
  password:useUser.password,
  projectCount: useUser.projectData.length
})

const fetchProjects = async () => {
  try {
    loading.value = true
    const res = await reqGetProject(paginationData.value.current, paginationData.value.pageSize)
    projects.value = res.data.records
    paginationData.value.total = res.data.total
  } finally {
    loading.value = false
  }
}

const handlePageChange = (val: number) => {
  paginationData.value.current = val
  fetchProjects()
}

const handleSizeChange = (val: number) => {
  paginationData.value.pageSize = val
  paginationData.value.current = 1  // 重置为第一页
  fetchProjects()
}

onMounted(fetchProjects)

const handleJoin = (row: any) => {
  ElMessageBox.confirm(`确认加入项目 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    const res = await reqJoinMemberProjectById(row.id)
    if (res.code === 200) {
      useUser.aboutAsyncRoutes()
      ElMessage.success('加入成功')
    }
  })
}

const handlerEdit = () => [
  dialogVisible.value = true
]

const handleSubmit = async () => {
  if (!useUser.userName) {
    ElMessage.warning('请输入用户名')
    return
  }

  if (!useUser.email) {
    ElMessage.warning('请输入邮箱')
    return
  }

  await ElMessageBox.confirm(`确认修改您的个人信息吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    const res = await reqUpdateUserInfo(useUser.id as number, {
      username:userInfo.value.name,
      email: userInfo.value.email,
      role: userInfo.value.role,
    })
    if (res.code === 200) {
      ElMessage.success('修改成功!请重新登录~')
      dialogVisible.value = false
      $router.push('/login')
    }
  })


}
</script>

<template>
  <el-row :gutter="20" class="top-row">
    <el-col :span="12">
      <el-card class="user-card" shadow="hover">
        <template #header>
          <el-text size="large">个人信息</el-text>
          <el-button type="primary" style="float: right;" @click="handlerEdit">编辑信息</el-button>
        </template>
        <el-row :gutter="20" align="middle">
          <el-col :span="4">
            <Avatar :name="useUser.userName" :size="80"></Avatar>
          </el-col>
          <el-col :span="20">
            <h3 class="user-name" :class="{ 'dark-name': !useSetting.isLight }">{{ useUser.userName }}</h3>
            <div class="user-role">
              <el-tag :type="useUser.role === 'admin' ? 'danger' : 'primary'">
                {{ useUser.role }}
              </el-tag>
            </div>
            <div class="user-stats">
              <el-icon>
                <FolderOpened />
              </el-icon>
              参与项目数：{{ useUser.projectData.length }}
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="calendar-card" shadow="hover">
          <el-calendar class="full-calendar">
            <template #date-cell="{ data }">
              <p :class="data.isSelected ? 'is-selected' : ''">
                {{ data.day.split('-').slice(1).join('-') }}
                {{ data.isSelected ? '✔️' : '' }}
              </p>
            </template>
          </el-calendar>
      </el-card>
    </el-col>
  </el-row>

  <el-card header="项目列表" shadow="hover" class="project-card">
    <el-table :data="projects" v-loading="loading" style="width: 100%" stripe border height="30vh">
      <el-table-column prop="id" label="项目ID" width="160" />
      <el-table-column prop="name" label="项目名称" width="220" />
      <el-table-column prop="description" label="项目描述" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="createdBy.username" label="创建人" width="180" />

      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button v-if="!useUser.projectData.some(project => project.id === row.id)" type="primary" size="small" @click="handleJoin(row)">加入</el-button>
          <el-button v-else disabled>已加入</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination class="pagination" :current-page="paginationData.current" :page-size="paginationData.pageSize"
      :total="paginationData.total" background @current-change="handlePageChange" @size-change="handleSizeChange"
      :page-sizes="[5, 10, 20, 30]" layout="total, sizes, prev, pager, next" style="margin-top: 10px;" />
  </el-card>

  <el-dialog v-model="dialogVisible" title="编辑信息" width="30%">
    <div class="avatar">
      <Avatar :name="useUser.userName" class="dialog_avatar" :size="80"></Avatar>
      <p class="dialog_name">{{ useUser.userName }}</p>
    </div>
    <el-form v-model="userInfo" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="userInfo.name" />
      </el-form-item>
      <el-form-item label="角色">
        <el-radio-group v-model="userInfo.role" v-if="useUser.role==='admin'">
          <el-radio label="admin"><el-tag type="danger">管理员</el-tag></el-radio>
          <el-radio label="user"><el-tag type="primary">普通用户</el-tag></el-radio>
        </el-radio-group>
        <el-tag v-else>{{ userInfo.role }}</el-tag>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="userInfo.email" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang='scss'>
.top-row {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.user-card,
.calendar-card {
  height: 50vh;
  border-radius: 8px;
  transition: all 0.3s;

  :deep(.full-calendar) {
    height: calc(50vh - 80px); // 增加减去的空间
    overflow: auto;
    
    .el-calendar {
      height: 100%;
      display: flex;
      flex-direction: column;
    }
    
    .el-calendar__body {
      padding: 0;
      flex: 1;
      overflow: auto;
    }
  }

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.user-card {
  .user-name {
    margin: 0 0 12px 0;
    font-size: 22px;
    color: #333;

    &.dark-name {
      color: #fff;
    }
  }



  .user-role {
    margin-bottom: 15px;
  }

  .user-stats {
    color: #409EFF;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

.project-card {
  height: 50vh;
  margin-top: 20px;
  border-radius: 8px;
}

.avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  text-align: center;

  .dialog_avatar {
    margin-bottom: 10px;
    border: none;
  }

  .dialog_name {
    font-size: 22px;

  }
}
</style>